package com.baikeyang.bike.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.baikeyang.bike.bean.BikeBean;
import com.baikeyang.bike.bean.ConvertLocalReuslt;
import com.baikeyang.bike.bean.UserAgent;
import com.baikeyang.bike.service.IXABikeService;
import com.baikeyang.bike.util.HttpClientUtils;
import com.baikeyang.bike.util.MapUtil;
import com.baikeyang.bike.util.StringUtil;
import com.baikeyang.bike.util.UserAgentUtil;

@Controller("bikeController")
@Scope(value="request")
@RequestMapping("/")
public class BikeController extends BaseController {
	
	private static Logger log = Logger.getLogger(BikeController.class);
	
	@Autowired
	private IXABikeService xaBikeService;
	
	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response, ModelMap map){
		UserAgent ua = UserAgentUtil.getUserAgent(request.getHeader("User-Agent"));
		if(null != ua && 
				(ua.getPlatformType().equals("Windows Phone") || ua.getPlatformType().equals("IOS"))
				){// 只允许Windows Phone 和 iPhone 终端访问
			return new ModelAndView("index");
		}
		map.put("ua", ua);
		return new ModelAndView("message");
	}
	
	
	
	@ResponseBody
	@RequestMapping(value = "getBikeSite", method = {RequestMethod.POST})
	public String getBikeSite(HttpServletRequest request, HttpServletResponse response){
		return parse2JsonArr(getBikeAll());
	}

	@ResponseBody
	@RequestMapping(value = "getAbnormalSite", method = {RequestMethod.POST,RequestMethod.GET})
	public String getBikeAllAbnormalSite(HttpServletRequest request, HttpServletResponse response){
		List<BikeBean> bikes = xaBikeService.getBikeAbnormalSite();
		bikes = bikeLocalConvert(bikes,null);
		return parse2JsonArr(bikes);
	}
	
	@ResponseBody
	@RequestMapping(value = "getNormalSite", method = {RequestMethod.POST,RequestMethod.GET})
	public String getBikeAllNormalSite(HttpServletRequest request, HttpServletResponse response){
		List<BikeBean> bikes = xaBikeService.getBikeNormalSite();
		bikes = bikeLocalConvert(bikes,null);
		return parse2JsonArr(bikes);
	}
	
	@ResponseBody
	@RequestMapping(value = "convertLocal", method = {RequestMethod.POST,RequestMethod.GET}) 
	public String getAMapLocalConvertBaiDuLocal(HttpServletRequest request, HttpServletResponse response, String locations){
		Map<String, String> parameterMap = new HashMap<String, String>();
		parameterMap.put("key", "6ff97f49dce4dc604d1a739c2a3a6f83");
		parameterMap.put("locations",locations);
		parameterMap.put("coordsys","baidu");
		parameterMap.put("output","JSON");
		String str = HttpClientUtils.doGet("http://restapi.amap.com/v3/assistant/coordinate/convert?parameters ", parameterMap);
		return str;
	}
	
	private List<BikeBean> getBikeAll() {
		List<BikeBean> bikes = new ArrayList<BikeBean>();
		try {
			bikes = bikeLocalConvert(xaBikeService.getAllBikes(),null);
		} catch (Exception e) {
			log.error("获取全部车站信息时发生异常", e);
		}
		return bikes;
	}
	
	@ResponseBody
	@RequestMapping(value = "synchronize", method = {RequestMethod.POST, RequestMethod.GET}, produces = { "application/json;charset=UTF-8" })
	public String synchronizeBikeSite(){
		xaBikeService.synchronizeBikeSite();
		return parse2Json("SUCCESS");
	}
	
	@ResponseBody
	@RequestMapping(value = "get/site/{siteId}", method = {RequestMethod.POST, RequestMethod.GET}, produces = { "application/json;charset=UTF-8" })
	public String getBikeSite(HttpServletRequest request, HttpServletResponse response, @PathVariable("siteId")String siteId){
		return parse2Json(xaBikeService.getBikeSiteById(siteId));
	}
	
	@ResponseBody
	@RequestMapping(value = "getSearch", method = {RequestMethod.POST,RequestMethod.GET},  produces = "application/json; charset=utf-8") 
	public String getSearchByLocalPosition(HttpServletRequest request, HttpServletResponse response, String lng, String lat, String radius){
		double cenLngX = 0;
		double cenLatY = 0;
		try {
			cenLngX = Double.parseDouble(lng);
			cenLatY = Double.parseDouble(lat);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		List<BikeBean> result = new ArrayList<BikeBean>();
		// TODO 获取所有车辆
		List<BikeBean> bikes = xaBikeService.getAllBikePostions();
		for (int i = 0; i < bikes.size(); i++) {
			BikeBean bike = bikes.get(i);
			if(null != bike){
				if(StringUtil.isNotEmpty(bike.getLongitude()) && StringUtil.isNotEmpty(bike.getLatitude())
						&& StringUtil.isNotEmpty(lng) && StringUtil.isNotEmpty(lat)){
					double bikeLngX = 0;
					double bikeLatY = 0;
					double bikeRadius = 0;
					try {
						bikeLngX = Double.parseDouble(bike.getLongitude());
						bikeLatY = Double.parseDouble(bike.getLatitude());
						bikeRadius = Double.parseDouble(radius);
					} catch (Exception e) {
						log.error(e.getMessage());
					}
					// 判断车辆是否在区域内
					if (MapUtil.isPointInCircleArea(bikeLngX, bikeLatY, cenLngX, cenLatY, bikeRadius)) {
						result.add(bike);
					}
				}
			}
		}
		result = bikeLocalConvert(result,null);
		return parse2JsonArr(result);
	}
	
	private static List<BikeBean> bikeLocalConvert(List<BikeBean> bikes, List<BikeBean> resules){
		boolean flag = false;
		if(null != bikes && bikes.size() > 0){
			flag = true;
		}
		
		List<BikeBean> result = resules;
		while (flag) {
			
			StringBuffer locations = new StringBuffer();
			List<BikeBean> convertList = new ArrayList<BikeBean>();
			for (int i = 0; i < bikes.size(); i++) {
				if(i < 40){
					if(null != bikes.get(i)){
						convertList.add(bikes.get(i));
						String lat = bikes.get(i).getLatitude();
						String lng = bikes.get(i).getLongitude();
						locations.append(lng+","+lat+";");
						bikes.remove(i);
						i--;
					}
				}else{
					break;
				}
				
			}
			
			ConvertLocalReuslt convertResult = convertLocal(locations);
			if(null != convertResult && convertResult.getStatus().equals("1")){
				String[] locationArray = convertResult.getLocations().split(";");
				for (int i = 0;i < convertList.size(); i++) {
					convertList.get(i).setLnglat(locationArray[i]);
					convertList.get(i).setLongitude(locationArray[i].split(",")[0]);
					convertList.get(i).setLatitude(locationArray[i].split(",")[1]);
				}
				if(null == result){
					result = new ArrayList<BikeBean>();
				}
				result.addAll(convertList);
			}
			if(bikes.size() > 0){
				bikeLocalConvert(bikes,result);
			}else{
				flag = false;
			}
			
		}
		return result;
	}
	
	private static ConvertLocalReuslt convertLocal(StringBuffer locations){
		Map<String, String> parameterMap = new HashMap<String, String>();
		parameterMap.put("key", "6ff97f49dce4dc604d1a739c2a3a6f83");
		parameterMap.put("locations",locations.toString());
		parameterMap.put("coordsys","baidu");
		parameterMap.put("output","JSON");
		String str = HttpClientUtils.doPost("http://restapi.amap.com/v3/assistant/coordinate/convert", null, parameterMap);
		//String str = HttpClientUtils.doGet("http://restapi.amap.com/v3/assistant/coordinate/convert", parameterMap);
		ConvertLocalReuslt result = JSON.parseObject(str, ConvertLocalReuslt.class);
		return result;
	}
	
	
	public static void main(String[] args) {
//		Map<String, String> parameterMap = new HashMap<String, String>();
//		parameterMap.put("key", "6ff97f49dce4dc604d1a739c2a3a6f83");
//		parameterMap.put("location","114.440986,30.61834");//114.440986,30.61834
//		parameterMap.put("output","JSON");
//		String str = HttpClientUtils.doGet("http://restapi.amap.com/v3/geocode/regeo?parameters", parameterMap);
//		System.out.println(str);
		
		String str = "Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; NOKIA; Lumia 929) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Mobile Safari/537.36 Edge/14.14393";
		UserAgent ua = UserAgentUtil.getUserAgent(str);
		System.out.println(ua);
		
	}
	
	
	
	
}
